package com.xm.bluetoothkotlin.search

import android.annotation.SuppressLint
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanSettings
import android.os.ParcelUuid
import com.blankj.utilcode.util.ThreadUtils
import com.xm.bluetoothkotlin.BluetoothManager
import java.util.*

/**
 * @创建者:小垚
 * @时间:2021/11/11
 *@描述: 蓝牙搜索
 */
object BluetoothSearch {
    private val searchCallback by lazy { BluetoothScanCallback() }

    //搜索状态
    private var status = BluetoothStatus.IDLE

    /**
     * 搜索
     */
    @SuppressLint("MissingPermission")
    fun search(uuids: MutableList<UUID>?, deviceName: String?, deviceMac: String?, timeLong: Long) {
        if (status == BluetoothStatus.SEARCH) {
            return
        }
        val filters = mutableListOf<ScanFilter>()
        uuids?.run {
            if (uuids.isNotEmpty()) {
                uuids.forEachIndexed { index, uuid ->
                    filters.add(
                        ScanFilter.Builder()
                            .setServiceUuid(ParcelUuid(uuid))
                            .build()
                    )
                }
            }
        }

        deviceName?.run {
            filters.add(
                ScanFilter.Builder()
                    .setDeviceName(this)
                    .build()
            )
        }

        deviceMac?.run {
            filters.add(
                ScanFilter.Builder()
                    .setDeviceAddress(this)
                    .build()
            )
        }

        notifyOnStartSearch()
        status = BluetoothStatus.SEARCH
        if (filters.isNotEmpty()) {
            val setting = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build()
            BluetoothManager.bluetoothAdapter.bluetoothLeScanner.startScan(filters, setting, searchCallback)
        } else {
            BluetoothManager.bluetoothAdapter.bluetoothLeScanner.startScan(searchCallback)
        }

        //时间到了暂停搜索
        ThreadUtils.runOnUiThreadDelayed({
            stopSearch()
        }, timeLong)
    }

    /**
     * 暂停搜索
     */
    @SuppressLint("MissingPermission")
    fun stopSearch() {
        status = BluetoothStatus.IDLE
        BluetoothManager.bluetoothAdapter.bluetoothLeScanner.stopScan(searchCallback)
        notifyOnStopSearch()
    }

    /**
     * 开始搜索蓝牙
     */
    private fun notifyOnStartSearch() {
        ThreadUtils.runOnUiThread {
            BluetoothManager.searchs.forEachIndexed { index, bluetoothScanCallback ->
                bluetoothScanCallback.onStartSearch()
            }
        }
    }

    /**
     * 结束搜索蓝牙
     */
    private fun notifyOnStopSearch() {
        ThreadUtils.runOnUiThread {
            BluetoothManager.searchs.forEachIndexed { index, bluetoothScanCallback ->
                bluetoothScanCallback.onStopSearch()
            }
        }
    }
}